package com.oyjd.framework.log;

import java.io.FileOutputStream;
import java.io.PrintStream;
import java.text.SimpleDateFormat;

import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.util.Log;

import com.oyjd.framework.Const;

/**
 * 重写日志工具类，方便日志输出控制或扩展为日志文件、日志流等输出
 * 
 * @author 欧建东
 * @email oyjd@163.com
 * 
 */
@SuppressLint("SimpleDateFormat")
public class MyLog {
	private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");// 日志文件名时间格式
	private static SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 日志输出信息时间格式

	private static final String TYPE_DEBUG = "debug";
	private static final String TYPE_INFO = "info";
	private static final String TYPE_WARN = "warn";
	private static final String TYPE_ERROR = "error";

	private static String LOG_ENCODING = "gb2312";// 日志输出的编码

	/**
	 * debug 输出
	 * 
	 * @param tag
	 * @param msg
	 */
	public static void d(String tag, String msg) {
		if (Const.LOG_FLAG) {
			Log.d(tag, msg);
			logFile(TYPE_DEBUG, tag, msg, null);
		}
	}

	/**
	 * info 输出
	 * 
	 * @param tag
	 * @param msg
	 */
	public static void i(String tag, String msg) {
		if (Const.LOG_FLAG) {
			Log.i(tag, msg);
			logFile(TYPE_INFO, tag, msg, null);
		}
	}

	/**
	 * warn 输出
	 * 
	 * @param tag
	 * @param msg
	 */
	public static void w(String tag, String msg) {
		if (Const.LOG_FLAG) {
			Log.w(tag, msg);
			logFile(TYPE_WARN, tag, msg, null);
		}
	}

	/**
	 * error 输出
	 * 
	 * @param tag
	 * @param msg
	 * @param tr
	 */
	public static void e(String tag, String msg, Throwable tr) {
		if (Const.LOG_FLAG) {
			Log.e(tag, msg, tr);
			logFile(TYPE_ERROR, tag, msg, tr);
		}
	}

	/**
	 * 记录到文件
	 * 
	 * @param tag
	 * @param msg
	 * @param tr
	 */
	private static void logFile(final String type, final String tag, final String msg, final Throwable tr) {
		new AsyncTask<Object, Integer, Object>() {
			@Override
			protected Object doInBackground(Object... params) {
				try {
					long time = System.currentTimeMillis();
					String fileName = type + sdf.format(time) + ".log";
					String path = Const.APP_LOG_DIR + fileName;
					//
					PrintStream ps = new PrintStream(new FileOutputStream(path, true), true, LOG_ENCODING);
					if (TYPE_ERROR.equals(type)) {
						ps.append("【时间】: " + sdf1.format(time) + "\r\n");
						ps.append("【标签】: " + tag + "\r\n");
						ps.append("【信息】: " + msg + "\r\n");
						ps.append("【轨迹】: ");
						tr.printStackTrace(ps);
						ps.append("\r\n\r\n");
					} else {
						ps.append(sdf1.format(time) + "  " + tag + "  " + msg + "\r\n");
					}
					ps.flush();
					ps.close();
				} catch (Exception err) {
					err.printStackTrace();
				}
				return null;
			}

			@Override
			protected void onPostExecute(Object result) {

			}
		}.execute();
	}
}
